package week2nd;

import java.util.EmptyStackException;

public class ArrayStack {

    private int maxSize;
    private int top;
    private Object[] arr;

    public ArrayStack(int size) {
        maxSize = size;
        top = -1;
        arr = new Object[maxSize];
    }

    public void push(Object value) {
        if (!isFull()) {
            top++;
            arr[top] = value;
        }
        else {
            ArrayStack as = new ArrayStack(maxSize + 5);
            for (int i = 0; i < maxSize; i++){
                as.arr[i] = arr[i];
            }
            top++;
            as.arr[top] = value;
            maxSize += 5;
            arr = as.arr;
        }
    }

    public Object pop() {
        if (!isEmpty()) {
            Object temp = arr[top];
            arr[top] = null;
            top--;
            return temp;
        }
        else {
            return 0;
        }
    }

    public Object peek() throws EmptyStackException {
        Object o;
        try {
            o = arr[top];
        }catch (ArrayIndexOutOfBoundsException e) {
            o = new String("栈为空.");
        }
        return o;
    }

    public boolean isFull() {
        return maxSize - 1 == top;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public int size() {
        int n = 0;
        do {
            n++;
        }while (arr[n] != null);
        return n;
    }

    public int getMaxSize() {
        return maxSize;
    }

    @Override
    public String toString() {
        String str = "";
        for (int i = 0; i < maxSize; i++) {
            if (arr[i] != null) {
                str += arr[i] + " ";
            }
        }
        return str;
    }
}
